#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: ZhengShiQi
@file: login_business.py
@time: 2025/8/27 17:06
@desc: 登录业务逻辑
"""
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.common.exceptions import TimeoutException, NoSuchElementException

from page.login.login_page import LoginPage


class LoginBusiness(LoginPage):
    """登录业务类"""

    def login(self, driver, username, password):
        """执行登录操作"""
        # 访问登录页面
        driver.get("https://www.mabangerp.com/index.htm")
        print(f"当前页面URL: {driver.current_url}")
        print(f"页面标题: {driver.title}")
        # 获取页面加载时间
        load_time = driver.execute_script("return performance.timing.loadEventEnd - performance.timing.navigationStart;")
        print(f"页面加载时间: {load_time}ms")
        
        # 最大化窗口
        driver.maximize_window()
        # 保存driver到实例变量，以便NewPageElement可以访问
        self.driver = driver
        
        self.login_button.click()
        # 输入用户名和密码
        self.username.send_keys(username)
        self.password.send_keys(password)
        
        # 点击登录按钮
        self.account_btn.click()
        # 检查是否登录成功
        try:
            # 尝试获取check元素，如果元素存在则登录成功
            self.check
            return True
        except (TimeoutException, NoSuchElementException):
            # 如果元素不存在，则登录失败
            return False
        except Exception as e:
            print(f"登录失败: {e}")
            return False
